package leetcode.median;

import java.util.Stack;

/**
 * ClassName: $394_EncodingString
 * Description:
 * date: 2022-02-20 16:55
 *
 * @author liyifan
 */
public class $394_DecodeString {
    public String decodeString(String s) {
        Stack<Character> stack = new Stack<>();
        int i = 0;
        while (i < s.length()) {
            if (s.charAt(i) != ']') {
                stack.push(s.charAt(i));
            } else {
                StringBuilder sb = new StringBuilder();
                while (stack.peek() != '[') {
                    sb.append(stack.pop());
                }
                stack.pop();

                int num = 0;
                int digit = 1;
                while (!stack.isEmpty() && Character.isDigit(stack.peek())) {
                    num += (stack.pop() - '0') * digit;
                    digit *= 10;
                }
                for (int k = 0;k < num;k++) {
                    for (int n = sb.length() - 1;n >= 0;n--){
                        stack.push(sb.charAt(n));
                    }
                }
            }
            i++;
        }

        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }
        return sb.reverse().toString();
    }
}
